//
//  MYPictureView.swift
//  swift2.0项目开始
//
//  Created by 龚昕炜 on 16/8/3.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

/** 边距 */
private let GXWPictureViewMargin: CGFloat = 10
/** Item间距 */
private let GXWPictureItemMargin: CGFloat = 5
/** 配图里的Cell/Item的宽高 */
private let GXWPictureItemWH: CGFloat = (UIScreen.mainScreen().bounds.width - 2 * GXWPictureViewMargin - 2 * GXWPictureItemMargin) / 3

private let MYPhotoViewReuseIdentifier = "MYPhotoViewReuseIdentifier"

class MYPictureView: UICollectionView {

    /** 接收到数据模型数组的时候 */
    var pic_urls: [MYPictureModel]? {
    
        didSet {
            
            let size = calculateViewSize()
            
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
            }
            
            /** 刷新数据 */
            reloadData()
        }
    }
    
    /** 布局 */
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func calculateViewSize()-> CGSize {
    
        /** 图片数量 */
        let count = pic_urls?.count
        
        if count == 1 {
            
            /** 1.获取url,只有一张图片，所以只有一个元素 */
            let URLString = pic_urls?.first?.thumbnail_pic
            
            /** 2.根据url从沙盒里获取图片 */
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(URLString)
            
            /** 根据图片返回图片的大小 */
            if image != nil {
            
                var size = image.size
                
                /** 限制最大最小size */
                if size.width < 50 {
                    
                    let width: CGFloat = 50
                    let height = 50 / size.width * size.height
                    
                    size.width = width
                    size.height = height
                } 
                flowLayout.itemSize = size
                /** 返回图片大小 */
                return size
            }
            /** 一般不会出现，如果出现了就给一个随便值 */
            return CGSize(width: GXWPictureItemWH, height: GXWPictureItemWH)
        } else {
            /** 重用问题 */
            flowLayout.itemSize = CGSize(width: GXWPictureItemWH, height: GXWPictureItemWH)
        }
        
        if count == 4 {
            let WH = GXWPictureItemWH * 2 + GXWPictureItemMargin
            return CGSize(width: WH, height: WH)
        }
        
        if count == 2 || count == 3 {
            return CGSize(width: screenBounds.width - 2 * GXWPictureViewMargin, height: GXWPictureItemWH)
        }
        
        if count == 5 || count == 6 {
            return CGSize(width: screenBounds.width - 2 * GXWPictureViewMargin, height: (GXWPictureItemWH + GXWPictureItemMargin) * 2)
        }
        
        if count == 7 || count == 8 || count == 9 {
            return CGSize(width: screenBounds.width - 2 * GXWPictureViewMargin, height: (GXWPictureItemWH + GXWPictureItemMargin) * 3)
        }
        
        return CGSizeZero
    }
    
    /** 设置collection */
    private func setUpUI() {
        
        dataSource = self
        scrollEnabled = false
        /** 注册 */
        self.registerClass(MYPictureViewCell.self, forCellWithReuseIdentifier: MYPhotoViewReuseIdentifier)
        
        flowLayout.itemSize = CGSize(width: GXWPictureItemWH, height: GXWPictureItemWH)
        flowLayout.minimumInteritemSpacing = GXWPictureItemMargin
        flowLayout.minimumLineSpacing = GXWPictureViewMargin
//        flowLayout.estimatedItemSize = CGSizeMake(375, 300)
    }
}

// MARK:-- 数据源方法
extension MYPictureView: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MYPhotoViewReuseIdentifier, forIndexPath: indexPath) as! MYPictureViewCell
        
        /** 传入数据模型 */
        cell.model = pic_urls![indexPath.item]
        
        return cell
    }
}

// MARK:-- 自定义cell
class MYPictureViewCell: UICollectionViewCell {

    var model: MYPictureModel? {
    
        didSet {
//            print(NSURL(string: (model!.thumbnail_pic)!))
            iconImageView.sd_setImageWithURL(NSURL(string: model?.thumbnail_pic ?? ""))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.cyanColor()
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    /** 设置cell */
    private func setUpUI() {
    
        contentView.addSubview(iconImageView)
    
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    /** 懒加载 */
    private var iconImageView: UIImageView = {

        let img = UIImageView()
        
        img.backgroundColor = UIColor.blackColor()
        
        return img
    }()
}
